using System.Collections;
using UnityEngine;

public class HommingMagic1 : MonoBehaviour
{
	public AttackInfo attackInfo;

	private Transform tf;

	private CircleCollider2D col;

	private Rigidbody2D rb;

	private Transform target;

	private Coroutine co;

	private string targetTagName;

	private float speed;

	private float rotationSpeed;

	private void Awake()
	{
		tf = base.transform;
		rb = GetComponent<Rigidbody2D>();
		col = GetComponent<CircleCollider2D>();
	}

	public void Init(Transform TF_Target, float forceX)
	{
		speed = Mathf.Abs(forceX * 1000f);
		rotationSpeed = speed * 0.002f;
		targetTagName = ((!TF_Target.gameObject.name.Contains("Player")) ? "Enemy" : "Player");
		attackInfo.power = 500;
		target = TF_Target;
		rb.velocity = new Vector2(forceX * 50f, 0f);
		co = StartCoroutine(MovingMissle());
		col.enabled = true;
		StartCoroutine(ExplosionTimer(4));
		Audio.instance.sfx[42].Play();
	}

	private void OnTriggerEnter2D(Collider2D other)
	{
		if (other.CompareTag(targetTagName))
		{
			attackInfo.force = rb.velocity;
			Player.instance.Damaged(tf.position, attackInfo);
			Generator.instance.SpawnObj(29, tf.position);
			Audio.instance.sfx[43].Play();
			base.gameObject.SetActive(false);
		}
	}

	private IEnumerator ExplosionTimer(int timer)
	{
		yield return new WaitForSeconds(timer);
		col.enabled = false;
		if (co != null)
		{
			StopCoroutine(co);
			co = null;
		}
		rb.velocity = new Vector2(0f, 0f);
		Generator.instance.SpawnObj(29, tf.position);
		Audio.instance.sfx[43].Play();
		base.gameObject.SetActive(false);
	}

	private IEnumerator MovingMissle()
	{
		Vector3 vectorToTarget = rb.velocity;
		float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * 57.29578f;
		Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
		base.transform.rotation = Quaternion.Slerp(base.transform.rotation, q, Time.fixedDeltaTime * 10000f);
		yield return new WaitForSeconds(0.3f);
		while (true)
		{
			vectorToTarget = target.position - base.transform.position;
			angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * 57.29578f;
			q = Quaternion.AngleAxis(angle, Vector3.forward);
			base.transform.rotation = Quaternion.Slerp(base.transform.rotation, q, Time.fixedDeltaTime * rotationSpeed);
			rb.velocity = base.transform.right * Time.fixedDeltaTime * speed;
			yield return new WaitForFixedUpdate();
		}
	}
}
